import os
from PyQt4 import QtCore, QtGui, uic
from datetime import date

class PrefWindow(QtGui.QDialog):
	def __init__(self, backend, path, USE_COMPILED_UI):
		QtGui.QMainWindow.__init__(self)
		if USE_COMPILED_UI:
			from prefs_ui import Ui_Dialog
			print "Using pre-compiled prefs UI"
			self.ui = Ui_Dialog()
		else:
			ui_class, widget_class = uic.loadUiType(os.path.join(path, "prefs.ui"))
			self.ui = ui_class()
		self.ui.setupUi(self)
		self.backend = backend
		
		#set input validators
		charVal = backend.CharValidator()
		fileVal = backend.FileNameValidator()
		#extVal = backend.PrefsExtensionValidator() #not working yet
		self.ui.text_numSeparator.setValidator(charVal)
		self.ui.text_monthDirSyntax.setValidator(fileVal)
		self.ui.text_imagesExt.setValidator(charVal)
		self.ui.text_videoExt.setValidator(charVal)
		
		self.updatePrefsGui(backend) #keep as the last line of __init__

	def on_buttonBox_accepted(self):
		self.backend.prefs["photoLibraryPath"] = str(self.ui.label_photo_library.text())
		self.backend.prefs["photoExtensions"] = self.backend.stringTuple(str(self.ui.text_imagesExt.text())) #Need to be saved as a tuple
		self.backend.prefs["videoExtensions"] = self.backend.stringTuple(str(self.ui.text_videoExt.text())) #Need to be saved as a tuple
		self.backend.prefs["renameStringNumPadding"] = int(self.ui.text_numPadding.text())
		self.backend.prefs["renameStringNumPaddingSeparator"] = str(self.ui.text_numSeparator.text())
		self.backend.prefs["monthDirFormat"] = str(self.ui.text_monthDirSyntax.text())
		
		#print self.printPrefs()
		
	def on_buttonBox_rejected(self):
		pass

	# reset prefs to default vaules
	def on_buttonBox_clicked(self, qbutton):
		if str(qbutton.text()) != "Restore Defaults":
			return
		self.backend.prefs = self.backend.defaultPrefs()
		self.backend.GROUP_SUBDIR_NAME = None
		self.updatePrefsGui(self.backend)

	def on_text_imagesExt_editingFinished(self):
		if not self.backend.stringTuple(str(self.ui.text_imagesExt.text())):# check if input is valid
			self.ui.text_imagesExt.setText(self.backend.stringTuple(self.localprefs["photoExtensions"])) # reset values if input is not correct
		self.localprefs["photoExtensions"] = self.backend.stringTuple(str(self.ui.text_imagesExt.text()))
		self.ui.text_imagesExt.setText(self.backend.stringTuple(self.localprefs["photoExtensions"])) #not currently needed
		
	def on_text_videoExt_editingFinished(self):
		if not self.backend.stringTuple(str(self.ui.text_videoExt.text())):# check if input is valid
			self.ui.text_videoExt.setText(self.backend.stringTuple(self.localprefs["videoExtensions"])) # reset values if input is not correct
		self.localprefs["videoExtensions"] = self.backend.stringTuple(str(self.ui.text_videoExt.text()))
		self.ui.text_videoExt.setText(self.backend.stringTuple(self.localprefs["videoExtensions"])) #not currently needed

	#TODO: check if padding is big enough right before importing
	def on_text_numPadding_textEdited(self):
		if not self.ui.text_numPadding.text() or not str(self.ui.text_numPadding.text()).isdigit():
			return
		if int(self.ui.text_numPadding.text()) > 10:
			self.ui.text_numPadding.setText("10")
		if int(self.ui.text_numPadding.text()) < 1:
			self.ui.text_numPadding.setText("1")
		self.localprefs["renameStringNumPadding"] = int(self.ui.text_numPadding.text())
		self.updateExampleLabel()
	def on_text_numPadding_editingFinished(self):
		if not self.ui.text_numPadding.text() or not str(self.ui.text_numPadding.text()).isdigit():
			self.ui.text_numPadding.setText(str(self.localprefs["renameStringNumPadding"]))

	def on_text_numSeparator_textEdited(self):
		if not self.ui.text_numSeparator.text():
			return

		self.localprefs["renameStringNumPaddingSeparator"] = str(self.ui.text_numSeparator.text())
		self.updateExampleLabel()

	def on_text_monthDirSyntax_textEdited(self):
		try:	date.today().strftime(str(self.ui.text_monthDirSyntax.text())) #test to see if syntax is valid
		except: return
		self.localprefs["monthDirFormat"] = str(self.ui.text_monthDirSyntax.text())
		self.updateExampleLabel()
		
	def on_text_monthDirSyntax_editingFinished(self):
		if not self.ui.text_monthDirSyntax.text():
			self.ui.text_monthDirSyntax.setText(self.backend.prefs["monthDirFormat"])
		try:
			date.today().strftime(str(self.ui.text_monthDirSyntax.text())) #test to see if syntax is valid
		except:
			self.ui.text_monthDirSyntax.setText(self.backend.prefs["monthDirFormat"])
		self.localprefs["monthDirFormat"] = str(self.ui.text_monthDirSyntax.text())
		
	def updateExampleLabel(self):
		path = self.backend.destPath(self.localprefs)
		filename = self.backend.generateFileName("photo.jpg", self.localprefs, 1)
		fullPath = os.path.join(path, filename)
		fontMetric = self.ui.label_examplePath.fontMetrics()
		s = fontMetric.elidedText(fullPath, 0, 300) #truncate if too wide
		self.ui.label_examplePath.setText('"'+s+'"')
	
	#Change the default Photo Library
	def on_button_browse_library_released(self):
		qpath = QtGui.QFileDialog.getExistingDirectory(self, self.tr('Select the destintion folder'), self.ui.label_photo_library.text())
		if not qpath: return
		path = os.path.normpath(str(qpath))
		self.ui.label_photo_library.setText(path)
		self.localprefs["photoLibraryPath"] = path
		self.updateExampleLabel()

	#update the gui to reflect the backend variables
	def updatePrefsGui(self, backend):
		self.ui.text_imagesExt.setText(backend.stringTuple(backend.prefs["photoExtensions"]))
		self.ui.text_videoExt.setText(backend.stringTuple(backend.prefs["videoExtensions"]))
		self.ui.text_numPadding.setText(str(backend.prefs["renameStringNumPadding"]))
		self.ui.text_numSeparator.setText(backend.prefs["renameStringNumPaddingSeparator"])
		self.ui.text_monthDirSyntax.setText(backend.prefs["monthDirFormat"])
		self.ui.label_photo_library.setText(backend.prefs["photoLibraryPath"])

		self.localprefs = {}
		for name in backend.prefs:
			self.localprefs[name] = backend.prefs[name]
		self.localprefs["rename"] = True
		self.localprefs["renameString"] = "file"
		self.updateExampleLabel()
	
	def printPrefs(self):
		print "SubDir\t", self.backend.GROUP_SUBDIR_NAME
		for key, value in self.backend.prefs.items():
			print key, "\t", value
		print "==================================\n"
